package com.example.widget.custom;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.customview.widget.ViewDragHelper;

import com.blankj.utilcode.util.ConvertUtils;

public class AnchorScrollBehavior extends CoordinatorLayout.Behavior<View> {
    private ViewDragHelper helper;
    private  int height=0;
    private View refView;//滑动缩放的子view
    public AnchorScrollBehavior(Context context, AttributeSet attrs) {
        super(context,attrs);
    }


    @Override
    public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
//       区分滑动方向
        if (helper==null){
            helper = ViewDragHelper.create(parent,1f,callback);
            refView = child;
            height = refView.getMeasuredHeight();
        }
        return super.onLayoutChild(parent, child, layoutDirection);
    }


    @Override
    public boolean onTouchEvent(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull MotionEvent ev) {
//      1:32:08
        if (helper == null)
            return false;
        helper.processTouchEvent(ev);
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull MotionEvent ev) {
        if (helper==null)
        return super.onInterceptTouchEvent(parent, child, ev);
        return helper.shouldInterceptTouchEvent(ev);
    }
//    1:23:31
    private ViewDragHelper.Callback callback=new ViewDragHelper.Callback() {
        @Override
        public boolean tryCaptureView(@NonNull View child, int pointerId) {
//          当前设置ViewDragHelper的view是否可以滑动
            return true;
        }
//    子view垂直滑动
    @Override
    public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
        ViewGroup.LayoutParams layoutParams = child.getLayoutParams();
        if (layoutParams.height<0){
            layoutParams.height=height;
        }
        layoutParams.height+=dy;//当前高度每次移动的距离
//        视频播放最小边界
//        if (ConvertUtils.dp2px())
        if (layoutParams.height<ConvertUtils.dp2px(200)){
             layoutParams.height=ConvertUtils.dp2px(200);
        }
        if (layoutParams.height>height){
            layoutParams.height=height;
        }
        refView.setLayoutParams(layoutParams);
        return top;
    }
};

}
